<?php

namespace App\controller;

use support\Redis;
use support\Request;
use think\facade\Db;
use Illuminate\Support\Env;
use app\controller\RestBase;
use crmeb\exceptions\AdminException;
use think\exception\ValidateException;
use App\service\goods\GoodsComposeServices;
use think\db\exception\{DataNotFoundException, DbException, ModelNotFoundException};

class GoodsComposeApi
{
    /**
     * 提交合成
     * @param Request $request
     * @return \support\Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function composeSubmit(Request $request)
    {
        $token = $request->header('XX-Token');
        $deviceType = $request->header('XX-Device-Type');

        $allowedDeviceTypes = ['mobile', 'android', 'iphone', 'ipad', 'web', 'pc', 'mac', 'wxapp', 'ios'];

        if (empty($token)) {
            return json(['code' => 0, 'msg' => '请传入XX-Token']);
        }

        if (empty($deviceType)) {
            return json(['code' => 0, 'msg' => '请传入XX-Device-Type']);
        }

        if (!in_array($deviceType, $allowedDeviceTypes)) {
            return json(['code' => 0, 'msg' => '设备类型错误']);
        }

        $user = Db::name('user_token')
            ->where('token', $token)
            ->where('device_type', $deviceType)
            ->find();

        if (!$user) {
            return json(['code' => 0, 'msg' => '请先登录', 'user' => $user]);
        }

        $userId = $user['user_id'];

        $data = [
            'id' => $request->post('id') ?? '', // 藏品id
            'num' => $request->post('num') ?? '', // 合成数量
        ];

        if (empty($data['id'])) {
            return json(['code' => 0, 'msg' => '请传入藏品id！']);
        }

        $goodsComposeServices = new GoodsComposeServices();

        try {
            $goodsComposeServices->composeSubmit((int)$userId, (int)$data['id']);
        } catch (AdminException $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        return json(['code' => 1, 'msg' => "合成成功!"]);
    }


    /**
     * jmeter测试 合成功能
     * @param Request $request
     * @return \support\Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function jmeterComposeSubmit(Request $request)
    {
        $userId = 314753846876442625;

        $data = [
            'id' => $request->get('id') ?? '', // 藏品id
            'num' => $request->get('num') ?? '', // 合成数量
        ];

        if (empty($data['id'])) {
            return json(['code' => 0, 'msg' => '请传入藏品id！']);
        }

        $goodsComposeServices = new GoodsComposeServices();

        try {
            $goodsComposeServices->composeSubmit($userId, (int)$data['id']);
        } catch (AdminException $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        return json(['code' => 1, 'msg' => "合成成功!"]);
    }

}
